<template>
  <doc-alert label="会员用户、标签、分组" url="https://doc.iocoder.cn/member/user/" />

  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="归属门店" prop="tenantIds">
            <el-select
              v-model="queryParams.tenantIds"
              placeholder="请选择归属门店"
              clearable
              multiple
            >
              <el-option
                v-for="dict in tenantList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="归属员工" prop="employeeId">
            <el-select v-model="queryParams.employeeId" placeholder="请选择归属员工" clearable>
              <el-option
                v-for="dict in employeeList"
                :key="dict.employeeId"
                :label="dict.employeeName"
                :value="dict.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="姓名昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              clearable
              placeholder="请输入姓名昵称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              clearable
              placeholder="手机号码"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="会员性别" prop="sex">
            <el-select v-model="queryParams.sex" placeholder="请选择会员性别" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="近期生日" prop="recentBirthdays">
            <el-select v-model="queryParams.recentBirthdays" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.METON_BIRTHDAY_PERIOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="用户等级" prop="levelId">
            <MemberLevelSelect v-model="queryParams.levelId" classStyle="w-100%" />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="付费会员" prop="memberShip">
            <el-select v-model="queryParams.memberShip" clearable>
              <el-option
                v-for="(dict, index) in [
                  {
                    label: '是',
                    value: true
                  },
                  {
                    label: '否',
                    value: false
                  }
                ]"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="会员状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择会员状态" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.METON_MEMBER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="欠款状态" prop="arrears">
            <el-select v-model="queryParams.arrears" placeholder="请选择欠款状态" clearable>
              <el-option
                v-for="(dict, index) in [
                  {
                    label: '有欠款',
                    value: true
                  },
                  {
                    label: '无欠款',
                    value: false
                  }
                ]"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="用户标签" prop="tagIds">
            <MemberTagSelect v-model="queryParams.tagIds" classStyle="w-100%" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="会员来源" prop="userSource">
            <el-select v-model="queryParams.userSource" placeholder="请选择会员来源" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="用户分组" prop="groupId">
            <MemberGroupSelect v-model="queryParams.groupId" classStyle="w-100%" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="到店时间" prop="activeTime">
            <el-date-picker
              v-model="queryParams.activeTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="注册时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="登录时间" prop="loginDate">
            <el-date-picker
              v-model="queryParams.loginDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              :disabled-date="disabledDate"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button v-hasPermi="['promotion:coupon:send']" @click="openCoupon"
              >发送优惠券</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <PureTableBar title="" :columns="columns" @refresh="handleQuery">
      <template #default="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="id"
          @selection-change="handleSelectionChange"
          align-whole="center"
          :loading="loading"
          :size="size"
          :data="list"
          :columns="dynamicColumns"
        >
          <template #nickname="scope">
            <div class="flex">
              <el-image
                :preview-teleported="true"
                :src="scope.row.avatar"
                class="w-[48px] h-[48px] m-r-10px rounded-4px align-middle"
              />
              <el-tooltip effect="dark" :content="scope.row.nickname" placement="top">
                <el-text>{{ nameFormat(scope.row.nickname) }}</el-text>
              </el-tooltip>
            </div>
          </template>
          <template #sex="scope">
            <dict-text :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
          </template>
          <template #weight="scope">
            <el-text v-if="scope.row.weight">{{ scope.row.weight }}KG</el-text>
          </template>
          <template #operation="scope">
            <div class="flex items-center justify-center">
              <el-button link type="primary" @click="openDetail(scope.row.id)">详情</el-button>
              <el-dropdown
                v-hasPermi="[
                  'member:user:update',
                  'member:user:update-level',
                  'member:user:update-point',
                  'pay:wallet:update-balance'
                ]"
                @command="(command) => handleCommand(command, scope.row)"
              >
                <el-button link type="primary">
                  <Icon icon="ep:d-arrow-right" />
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="checkPermi(['member:user:update'])"
                      command="handleUpdate"
                    >
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="checkPermi(['member:user:update-level'])"
                      command="handleUpdateLevel"
                    >
                      修改等级
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="checkPermi(['member:user:update-point'])"
                      command="handleUpdatePoint"
                    >
                      修改积分
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="checkPermi(['pay:wallet:update-balance'])"
                      command="handleUpdateBlance"
                    >
                      修改余额
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="checkPermi(['trade:brokerage-user:update-bind-user'])"
                      command="handleBrokerage"
                    >
                      设置推广资格
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <template #empty>
            <Empty />
          </template>
        </pure-table>
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="getList"
        />
      </template>
    </PureTableBar>
    <!-- 分页 -->
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 修改用户等级弹窗 -->
  <UserLevelUpdateForm ref="updateLevelFormRef" @success="getList" />
  <!-- 修改用户积分弹窗 -->
  <UserPointUpdateForm ref="updatePointFormRef" @success="getList" />
  <!-- 修改用户余额弹窗 -->
  <UserBalanceUpdateForm ref="UpdateBalanceFormRef" @success="getList" />
  <!-- 发送优惠券弹窗 -->
  <CouponSendForm ref="couponSendFormRef" />
</template>
<script lang="ts" setup>
import * as UserApi from '@/api/member/user'
import UserForm from './UserForm.vue'
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberLevelSelect from '@/views/member/level/components/MemberLevelSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import UserLevelUpdateForm from './components/UserLevelUpdateForm.vue'
import UserPointUpdateForm from './components/UserPointUpdateForm.vue'
import UserBalanceUpdateForm from './components/UserBalanceUpdateForm.vue'
import { CouponSendForm } from '@/views/mall/promotion/coupon/components'
import { checkPermi } from '@/utils/permission'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as BrokerageUserApi from '@/api/mall/trade/brokerage/user'
import { PureTableBar } from '@/components/RePureTableBar'
import { nameFormat } from '@/utils/formatter'

import * as ShopUserApi from '@/api/shop/system/user/index'
import { defaultShortcuts } from '@/utils/formatTime'
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'MemberUser' })
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: undefined,
  mobile: undefined,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: undefined,
  groupId: undefined,
  userSource: undefined,
  tenantIds: [],
  employeeId: '',
  memberShip: undefined,
  recentBirthdays: undefined,
  status: undefined,
  arrears: undefined,
  sex: undefined,
  activeTime: []
})
const queryFormRef = ref() // 搜索的表单
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const UpdateBalanceFormRef = ref() // 修改用户余额表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组
const tableRef = ref()
import { useUser } from './utils/hook'
const { columns } = useUser()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetprops()
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  console.log(rows)
  selectedIds.value = rows.map((row) => row.id)
}

/** 发送优惠券 */
const couponSendFormRef = ref()
const openCoupon = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要发送优惠券的用户')
    return
  }
  couponSendFormRef.value.open(selectedIds.value)
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      UpdateBalanceFormRef.value.open(row.id)
      break
    case 'handleBrokerage':
      handleBrokerageEnabledChange(row)
      break

    default:
      break
  }
}
/** 推广资格：开通/关闭 */
const handleBrokerageEnabledChange = async (row: BrokerageUserApi.BrokerageUserVO) => {
  try {
    // 二次确认
    const text = row.brokerageEnabled ? '开通' : '关闭'
    await message.confirm(`确认要${text}"${row.nickname}"的推广资格吗？`)
    // 发起修改
    await BrokerageUserApi.updateBrokerageEnabled({ id: row.id, enabled: row.brokerageEnabled })
    message.success(text + '成功')
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.brokerageEnabled = !row.brokerageEnabled
  }
}

/** 初始化 **/
const employeeList = ref([])
/** 门店精简列表 */
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any[]>([])
const getTenantList = async () => {
  let params = {
    tenantType: 4
  }
  const data = await TenantApi.getChildTenantWithPostList(params)

  data.map((ele) => {
    tenantList.value.push({
      name: ele.name,
      id: ele.id
    })
  })
}

onMounted(async () => {
  getList()
  employeeList.value = await ShopUserApi.getEmployeeList()
  getTenantList()
})
</script>
